import 'package:flutter_todolist/db/table/user_table.dart';
import 'package:flutter_todolist/pages/home/task_overview.dart';
import 'package:flutter_todolist/utils/common.dart';
import 'package:flutter_todolist/utils/get_storage.dart';
import 'package:get/get.dart';

import '../../db/db.dart';
import '../../db/table/task_table.dart';

class TaskController extends GetxController {
  final taskList = <Task>[].obs;
  late TaskTable taskTable;
  final currentTaskTypeIndex = 0.obs;
  // final taskOverViewCtrl = Get.put(TaskOverViewController());

  @override
  void onInit() {
    taskTable = ToDoDB().taskTable;
    getTask();
    super.onInit();
  }

  addTask(Task task) {
    taskList.add(task);
    taskTable.insertItem(task.toJson());
    taskList.sort((a,b) => a.expiresTime!.compareTo(b.expiresTime!));
    update();
    // taskOverViewCtrl.getTaskStat();
  }

  updateTask(Task task) {
    for (int i=0; i< taskList.length; i++) {
      if (taskList[i].tid == task.tid) {
        taskList.replaceRange(i, i+1, [task]);
      }
    }
    taskTable.updateItem(task.tid, task.toJson());
    // 手动更新，因为Task没有转为obs对象
    update();
  }

  getTask() async {
    User currentUser = User.fromJson(AppStorage().read(AppStorage.UserInfo));
    List<Map> taskMaps = await ToDoDB().taskTable.queryList(
      where: "createBy = ?",
      whereArgs: [currentUser.userId!],
      orderBy: 'expiresTime asc'
    );
    taskList.clear();
    taskList.addAll(
      taskMaps.map((e) => Task.fromJson(e))
    );
  }

  deleteTask(Task task) {
    taskList.removeWhere((element) => element.tid == task.tid);
    taskTable.deleteItem(task.tid);
  }

  bool hadTask(Task task) {
    bool exist = false;
    for (var element in taskList) {
      if (element.title == task.title) {
        exist = true;
        return exist;
      }
    }
    return exist;
  }

  @override
  void onClose() {
    super.onClose();

  }

}